import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/providers/providers.dart';
import 'package:merchants/utils/we-chat-auth-result.dart';

class WeChatManager {
  static const MethodChannel _channel = MethodChannel(
    'com.shopthrive.merchants/wechat',
  );
  static StreamController<WeChatAuthResult> _responseController =
      StreamController.broadcast();
  static bool _initialized = false;

  static Future<void> init(ProviderContainer container) async {
    if (_initialized) {
      return;
    }
    
    // 检查StreamController状态，如果已关闭则重新创建
    if (_responseController.isClosed) {
      _responseController = StreamController.broadcast();
    }
    
    _channel.setMethodCallHandler((call) async {
      if (call.method == 'onWeChatResponse') {
        final Map<dynamic, dynamic> args =
            call.arguments as Map<dynamic, dynamic>;
        final int errCode = args['errCode'] as int;
        final String? code = args['code'] as String?;
        final String? state = args['state'] as String?;


        if (code != null) {
          try {
            final weChatService = container.read(weChatServiceProvider);
            final authResult = await weChatService.getUserInfoWithCode(code);
            
            // 检查StreamController状态
            if (!_responseController.isClosed) {
              _responseController.add(authResult);
            } else {
              print('DEBUG: StreamController已关闭，无法发送结果');
            }
          } catch (e) {
            if (!_responseController.isClosed) {
              _responseController.add(
                WeChatAuthResult(success: false, errorMessage: e.toString()),
              );
            }
          }
        } else {
          String errorMessage;
          switch (errCode) {
            case 0:
              errorMessage = '登录成功';
              break;
            case -2:
              errorMessage = '登录取消';
              break;
            case -4:
              errorMessage = '登录被拒绝';
              break;
            case -1:
              errorMessage = '登录失败，未知错误';
              break;
            case -3:
              errorMessage = '请安装微信客户端';
              break;
            default:
              errorMessage = '登录失败，请重试 (错误码: $errCode)';
          }
          if (!_responseController.isClosed) {
            _responseController.add(
              WeChatAuthResult(success: false, errorMessage: errorMessage),
            );
          }
        }
      }
    });
    _initialized = true;
  }

  static Future<bool> isWeChatInstalled() async {
    try {
      bool result = await _channel.invokeMethod('isWeChatInstalled');
      return result;
    } catch (e) {
      rethrow;
    }
  }

  static Future<bool> login() async {
    try {
      bool result = await _channel.invokeMethod('login');
      return result;
    } catch (e) {
      rethrow;
    }
  }

  static Stream<WeChatAuthResult> get authResponseStream {
    return _responseController.stream;
  }

  static void dispose() {
    if (!_responseController.isClosed) {
      _responseController.close();
    } else {
    }
    // 重新创建一个新的StreamController，而不是重置初始化标志
    _responseController = StreamController.broadcast();
    _initialized = false;
  }
}
